package cn.xshi.actuator.worker;

import cn.xshi.actuator.vo.ActuatorForm;
import cn.xshi.actuator.util.ActConstant;
import cn.xshi.actuator.util.ActuatorSDKUtil;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.base.InitBean;
import cn.xshi.common.util.GetClientIp;
import cn.xshi.common.util.RestTemplateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @Desc 与WEB服务Server建立捂手操作
 * @Author 邓纯杰
 * @CreateTime 2013-10-05 17:15:42
 */
@Component
@Slf4j
@Order(-1)
@Data
public class Handshake implements CommandLineRunner {

    @Value("${jehc.omp.actuator.client.uri.hasPrefixApplicationName:false}")
    private Boolean hasPrefixApplicationName;//客户端web应用Uri接口地址是否包含应用名

    @Value("${jehc.omp.actuator.client.uri.clientHttpPrefix:http}")
    private String clientHttpPrefix;//客户端web应用Uri接口前缀采用http还是https 默认http

    @Value("${jehc.omp.actuator.client.uri.keepTimes:300000}")
    private Integer keepTimes;//心跳连接服务端，默认5分钟一次(1000*60*5)

    @Value("${jehc.omp.actuator.client.uri.enabled:true}")
    private Boolean enabled;//SDK是否禁用 true开启 false关闭

    @Value("${jehc.omp.actuator.client.uri.address:}")
    private String address;//服务端地址

    @Value("${jehc.omp.actuator.client.uri.enabled:true}")
    private Boolean enableServerName;//使用服务名为连接地址（微服务版本使用）

    @Resource
    RestTemplateUtil restTemplateUtil;

    @Resource
    InitBean initBean;

//    @Resource
//    private  HttpServletRequest request;

    @Resource
    ActuatorSDKUtil actuatorSDKUtil;

    @Override
    public void run(String... args) throws Exception {
        log.info("进入捂手操作！");
        execute();
    }

    /**
     * 握手
     */
    public void execute() {
        try {
//            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            RequestContextHolder.setRequestAttributes(sra,true);
            new Thread(new HandshakeRunnable()).start();
        }catch (Exception e){
            log.warn("未能执行捂手操作！");
        }
    }

    /**
     * 建立服务端连接
     */
    class HandshakeRunnable implements Runnable{
        public void run(){
            try {
                while (true){
                    try {
                        if(getEnabled()) {
                            handshake();
                        }
                    }catch (Exception e){
                        log.error("建立与jehc-actuator-server失败，信息：",e);//生成环境不打印
                    }finally {
                        Thread.sleep(getKeepTimes());
                    }
                }
            }catch (Exception e){
                log.error("建立与jehc-actuator-server失败，信息：",e);//生成环境不打印
            }
        }
    }

    /**
     * 建立捂手
     */
    private void handshake(){
        //手动设置秘钥
//        Map<String,String> map = new HashMap<>();
//        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
//        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        ActuatorForm actuatorForm = new ActuatorForm();
        actuatorForm.setPort(actuatorSDKUtil.getLocalPort());
        actuatorForm.setClientIp(GetClientIp.getLocalIp());
        actuatorForm.setEnv(actuatorSDKUtil.getEnviron());
        actuatorForm.setApplicationName(actuatorSDKUtil.getProjectName());
        actuatorForm.setClientHttpPrefix(getClientHttpPrefix());
        actuatorForm.setHasPrefixApplicationName(hasPrefixApplicationName);
//        BaseResult baseResult = restTemplateUtil.post(getAddress()+"/actuator/server/upload",BaseResult.class,actuatorForm, restTemplateUtil.setHeaders(request,map));
        BaseResult baseResult = null;
        if(getEnableServerName()){
            baseResult = restTemplateUtil.post(restTemplateUtil.restOMPUrl()+ ActConstant.ACTUATOR_UPLOAD,BaseResult.class,actuatorForm);
        }else {
            baseResult = restTemplateUtil.post(getAddress()+ ActConstant.ACTUATOR_UPLOAD,BaseResult.class,actuatorForm);
        }
        if(null != baseResult && baseResult.getSuccess()){
            log.info("建立actuator-server成功！");
        }else{
            log.warn("建立actuator-server失败！");
        }
    }
}
